package com.atguigu.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author: bie
 * @create: 2021-07-12 21:56
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("insert 自动填充 ......");
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "deleted", Boolean.class, false);

        // // strictInsertFill方法开销很大,为了防止开销过大
        // // 优化1: 判断是否具备author属性,是否有author的setter方法
        // boolean hasAuthor = metaObject.hasSetter("author");
        // if (hasAuthor) {
        //     log.info("start insert fill author....");
        //     this.strictInsertFill(metaObject, "author", String.class, "别哥");
        // }
        //
        // // 优化2: 判断age是否赋值
        // // 别忘了 在age字段上加注解 @TableField(value = "age", fill = FieldFill.INSERT)
        // Object age = this.getFieldValByName("age", metaObject);
        // if (age == null) {
        //     log.info("start insert fill age....");
        //     this.strictInsertFill(metaObject, "age", String.class, "18");
        // }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("update 自动填充 ......");
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    }
}